<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        /* 
            时间：O(N)
            空间：O(N)
        */
        function TreeNode(val) {
            this.val = val;
            this.left = null;
            this.right = null;
        }
        var a = new TreeNode(3)
        var b = new TreeNode(5)
        var c = new TreeNode(1)
        var d = new TreeNode(6)
        var e = new TreeNode(2)
        var f = new TreeNode(0)
        var g = new TreeNode(8)
        var h = new TreeNode(7)
        var i = new TreeNode(4)

        a.left = b
        a.right = c
        b.left = d
        b.right = e
        c.left = f
        c.right = g
        e.left = h
        e.right = i


        // 这题需要后序遍历就可以，理解递归就可以，不需要迭代
        // 为什么前序不可以呢？
        var lowestCommonAncestor = function(root, p, q) {
            function travelTree (root, p, q) {
                // 递归终止条件，找到q或者p，返回这个节点
                if (root === p || root === q || root === null) {
                    return root
                }
    
                // 左右都要递归，递归整棵树
                let left = lowestCommonAncestor(root.left, p, q)
                let right = lowestCommonAncestor(root.right, p, q)
    
                // 如果left和right都不为null，返回root，表示当前节点是left和right的最近公共祖先
                if (left !== null && right !== null) {
                    return root
                }
                // left不为null 而right为null时，返回left
                if (left !== null && right === null) {
                    return left
                } else if (left === null && right !== null) {
                    return right
                } else {
                    return null
                }
            }
            return travelTree(root, p, q)
        };
        // console.log(lowestCommonAncestor(a, b, i));
        console.log(lowestCommonAncestor(a, d, e));
    </script>
</body>

</html>